<?php

namespace app\common\model;

use think\Db;
use think\Exception;
use think\Model;


class TeamMember extends Model
{

    

    

    // 表名
    protected $name = 'team_member';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
		'status_text'
    ];
	
    const STATUS_NORMAL = 1;
    const STATUS_DEL = 0;
    
    public static $statusList = [
    	self::STATUS_NORMAL => '正常',
	    self::STATUS_DEL => '已删除'
    ];
    
    public function getStatusTextAttr($value, $data) {
    	$value = $value ? : $data['status'];
    	$list = self::$statusList;
    	return $list[$value] ?? '';
    }
	
	public function plan() {
		return $this->belongsTo('businessPlan', 'business_plan_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	public function team() {
		return $this->belongsTo('team', 'team_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	public function user() {
		return $this->belongsTo('user', 'user_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	/**
	 * 加入战队
	 * @param $planId 活动ID
	 * @param $teamId 战队ID
	 * @param $userId 用户ID
	 * @return bool
	 * @throws \think\exception\PDOException
	 */
	public function joinTeam($planId, $teamId, $userId) {
		$this->startTrans();
		try {
			
			//添加成员
			$res = $this->isUpdate(false)
				->save([
					'business_plan_id' => $planId,
					'team_id' => $teamId,
					'user_id' => $userId,
				]);
			
			if(!$res) {
				throw new Exception('加入战队出错');
			}
			
			//添加战队人数
			$teamRes = Db::name('team')
				->where(['id' => $teamId])
				->setInc('member');
			if(!$teamRes) {
				throw new Exception('添加战队数量出错');
			}
			
			$this->commit();
			return true;
		} catch (Exception $e) {
			$this->rollback();
			$this->error = $e->getMessage();
			return false;
		}
	}




}
